package com.tjf.record.xunfei;

import android.util.Log;

import com.tjf.record.MySocketCallBack;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class YjhWebSocketMager {
    //    private static String BASE_URL = "wss://rtasr.xfyun.cn/v1/ws";
    //ws://192.168.124.7:8888
//    private static String BASE_URL = "ws://192.168.124.7:8888?";
    private static String BASE_URL = "ws://150.158.100.130:9399/dotcwsasr?";
//    private static String BASE_URL = "ws://192.168.124.111:8080/spring-ws/path?";
//    private static String BASE_URL = "ws://wswatch.yuzhouxiong.net/asr";

    //    ws://150.158.100.130:9399/dotcwsasr?lanid=x&userid=xxx&token=xxxx&sid=xxxxx
    private static String ORIGIN = "https://rtasr.xfyun.cn/v1/ws";

    final SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS");

    MyWebSocketClient client;

    private MySocketCallBack myCallBack;

    private static int code = 1;
    private int Begin = 0;

    public void initWebSocket(String userid, String token, MySocketCallBack myCallBack) {
        initWebSocket(userid, token, "0", myCallBack);
    }

    public void initWebSocket(String userid, String token, String lang, MySocketCallBack myCallBack) {
        initWebSocket(userid, token, lang, "yzx123456789", myCallBack);
    }


    public void initWebSocket(String userid, String token, String lang, String sid, MySocketCallBack myCallBack) {
        this.myCallBack = myCallBack;
        URI url = null;
        try {

            url = new URI(BASE_URL + "lanid=" + lang + "&userid=" + userid + "&token=" + token + "&sid=" + sid);
//            url = new URI(BASE_URL);

            DraftWithOrigin draft = new DraftWithOrigin(ORIGIN);
            CountDownLatch handshakeSuccess = new CountDownLatch(1);
            CountDownLatch connectClose = new CountDownLatch(1);
            client = new MyWebSocketClient(url, draft, handshakeSuccess, connectClose);
            System.out.println("测试" + url);
            client.connect();
            // 等待握手成功
            handshakeSuccess.await();

        } catch (URISyntaxException e) {
            Log.d("WebSocketMager", "Connection error: ", e);
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }


    }


    public void sendBuff(byte[] bytes) {
        if (client != null) {
            Log.d("WebSocketMager", "=发送数据=");
            client.send(bytes);
        }
    }


    public void close() {
        // 关闭 WebSocket 连接
        if (client != null) {
            client.close();
            client = null;
        }
    }

    public String getCurrentTimeStr() {
        return sdf.format(new Date());
    }

    String currentResult;

    public class MyWebSocketClient extends WebSocketClient {

        private CountDownLatch handshakeSuccess;
        private CountDownLatch connectClose;

        public MyWebSocketClient(URI serverUri, Draft protocolDraft, CountDownLatch handshakeSuccess, CountDownLatch connectClose) {
            super(serverUri, protocolDraft);
            this.handshakeSuccess = handshakeSuccess;
            this.connectClose = connectClose;
            if (serverUri.toString().contains("wss")) {
                trustAllHosts(this);
            }
        }

        @Override
        public void onOpen(ServerHandshake handshake) {
            System.out.println(getCurrentTimeStr() + "\t连接建立成功！");
            Begin = 0;
            myCallBack.onStart();
            handshakeSuccess.countDown();
        }

        public String getContent(String message) {
            StringBuilder resultBuilder = new StringBuilder();
            try {
                JSONObject messageObj = new JSONObject(message);
                String result = messageObj.getString("result");
                code = 1;
                //判断是否包含这个
                if (messageObj.has("meetlog")) {
                    Log.d("WebSocketMager", result + "====新的一句话开始了  ==：");
                    code = 0;
                }
                int errCode = messageObj.getInt("errCode");
                if (errCode == 0) {
                    code = 0;
                }
                resultBuilder.append(result);
            } catch (Exception e) {
                return message; // 返回原始消息
            }
            return resultBuilder.toString();
        }


        @Override
        public void onMessage(String msg) {
            Log.d("WebSocketMager", "msg=====: " + msg);
            JSONObject msgObj = null;
            try {
                msgObj = new JSONObject(msg);


                String data = msgObj.getString("result");
                if (data != null) {
                    Log.d("WebSocketMager", "111111");
                    JSONObject object = new JSONObject();
                    try {
                        object.put("data", getContent(msg)); /// getContent(data)
                        object.put("code", code);
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                    myCallBack.onSuccess(object);
                    // 转写结果
//                    System.out.println(getCurrentTimeStr() + "\tresult: " + getContent(data));
                } else {
                    // 处理 data 为 null 的情况
                    Log.d("WebSocketMager", getCurrentTimeStr() + "\tdata 为 null，无法处理结果");
                }
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }


        @Override
        public void onError(Exception e) {
            handshakeSuccess.countDown();
            Log.d("WebSocketMager", getCurrentTimeStr() + "\t连接发生错误：" + e.getMessage() + ", " + new Date());
            JSONObject object = new JSONObject();
            try {
                object.put("wesocketError", "连接发生错误");
            } catch (JSONException ex) {
                throw new RuntimeException(ex);
            }
            myCallBack.onFail(object);
        }

        @Override
        public void onClose(int arg0, String arg1, boolean arg2) {
            handshakeSuccess.countDown();
            Log.d("WebSocketMager", getCurrentTimeStr() + "\t链接关闭");
            connectClose.countDown();
            JSONObject object = new JSONObject();
            try {
                object.put("wesocketError", "链接关闭");
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
            myCallBack.onComplete();

        }

        @Override
        public void onMessage(ByteBuffer bytes) {
            try {
                Log.d("WebSocketMager", getCurrentTimeStr() + "\t服务端返回：" + new String(bytes.array(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        public void trustAllHosts(MyWebSocketClient appClient) {
            Log.d("WebSocketMager", "wss");
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[]{};
                }

                @Override
                public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    // TODO Auto-generated method stub

                }

                @Override
                public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    // TODO Auto-generated method stub

                }
            }};

            try {
                SSLContext sc = SSLContext.getInstance("TLS");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                appClient.setSocket(sc.getSocketFactory().createSocket());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
